# Add project root to system path
import sys, os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(PROJECT_ROOT)
LIB_ROOT = os.path.join(PROJECT_ROOT,'lib')
sys.path.append(LIB_ROOT)

# Stuff for connecting to Google AppEngine
import getpass
def get_credentials():
  filename = os.path.join(os.path.dirname(__file__), 'saved_auth')
  try:
    f = open(filename)
    data = f.read().strip()
    appengine_path, app_id, appengine_host, username, password, host = data.split('\n')
  
  except (ValueError, AttributeError, IOError):
    appengine_path = raw_input("AppEngine install location (e.g. ~/google_appengine/) : ")
    app_id = raw_input("App ID (e.q. squirreltracker) : ")
    appengine_host = raw_input("AppEngine host location (e.g. app.appspot.com) : ")
    username = raw_input("Username (doesn't much matter for localhost) : ")
    password = getpass.getpass("Password (doesn't much matter for localhost) : ")
    host = raw_input("URL to get to this remote app (e.g. localhost:8081) : ")
    
    try:
      f = open(filename, 'w')
      f.write("\n".join([appengine_path, app_id, appengine_host, username, password, host]))
      f.close()
    except IOError:
      print "WARNING: Unable to save authentication data"
  
  return appengine_path, app_id, appengine_host, username, password, host


appengine_path, app_id, appengine_host, username, password, host = get_credentials()

import consts
consts.app_id = app_id
consts.appengine_host = appengine_host
consts.host = host
consts.appengine_path = appengine_path

auth_func = (lambda : (username, password))

# Import Google stuff and do actual connection to AppEngine
sys.path.append(appengine_path)
yaml_path = os.path.join(appengine_path, 'lib', 'yaml', 'lib')
sys.path.append(yaml_path)
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.ext import db
import yaml
remote_api_stub.ConfigureRemoteDatastore(app_id, '/remote_api', auth_func, appengine_host)

# Set / get token
from app.models.batch import Worker
Worker.register(host)

from application import app

if __name__ == "__main__":
  app.run()
else:
  application = app.wsgifunc()
